import { loginApi, getUserInfo, logoutApi } from "@/api/login";
import { delToken } from "@/utils/auth";
import storage from "@/utils/storage";

export default {
  namespaced: true,

  state() {
    return {
      token: storage.get("token") || "", // 用户token
      info: null, // 用户信息
      menus: [], // 用户菜单信息集合
    };
  },

  getters: {
    authRoutes(state) {
      return state.menus.filter((item) => item.type === 1);
    },

    // 按钮权限 ['base', 'base']
    permissions(state) {
      // perms: "base"    "base,hello"
      const result = [];
      state.menus
        .filter((item) => item.type === 2)
        .forEach((item) => {
          const perms = item.perms.split(",");
          result.push(...perms);
        });

      return result;
    },
  },

  mutations: {
    setToken(state, payload) {
      state.token = payload;
      // 写入本地存储
      // setToken(payload);
    },

    setInfo(state, payload) {
      state.info = payload;
    },

    setMenus(state, payload) {
      state.menus = payload;
    },

    clear(state) {
      state.token = "";
      state.info = null;
      state.menus = [];
      delToken();
    },
  },

  actions: {
    // 登录动作
    async login({ commit }, payload) {
      const result = await loginApi(payload);

      // 写入 token
      storage.set("token", result.token, result.expire);
      // 写入 refreshToken
      storage.set("refreshToken", result.refreshToken, result.refreshExpire);
      commit("setToken", result.token);
    },

    // 获取用户信息动作
    async getInfo({ commit }) {
      const result = await getUserInfo();
      // console.log("result", result);
      commit("setInfo", result.info);
      commit("setMenus", result.menus);

      // 组装好有权限的路由数据并返回
      return result.menus.filter((item) => item.type === 1);
    },

    // 登出动作
    async logout({ commit }) {
      // 调用接口
      await logoutApi();
      // 清理数据
      commit("clear");
    },
  },
};
